#include <bits/stdc++.h>
using namespace std;



class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int len = nums.size();
        int ans = nums[0]+nums[1]+nums[2];
        for(int first=0; first<len; ++first){
            int second = first+1;
            int third = len - 1;
            while(second < third){
                int sum = nums[first] + nums[second] + nums[third];
                if(sum > target) --third;
                if(sum < target) ++second;
                if(abs(ans-target) > abs(sum-target)) ans = sum;
                if(target - sum == 0) break;
            }
        }
        return ans;
    }
};

int main(){
    vector<int> nums = {-1,2,1,-4};
    Solution solution;
    cout<<solution.threeSumClosest(nums, 1);
    return 0;
}